﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Reflection;

namespace Common.Expansion
{
    public static class EntityEx
    {
        public static List<T> ToEntityList<T>(this DataTable dt) where T : EntityObject
        {
            List<T> list = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(ToEntity<T>(row));
            }
            return list;
        }

        /// <summary>
        /// ToEntityList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="key">做为key的列名 ： “uid”</param>
        /// <returns></returns>
        public static Dictionary<string, T> ToEntityList<T>(this DataTable dt, string key) where T : EntityObject
        {
            Dictionary<string, T> dict = new Dictionary<string, T>();
            foreach (DataRow row in dt.Rows)
                dict.Add(row[key.ToString()].ToString(), ToEntity<T>(row));
            return dict;
        }

        public static T ToEntity<T>(this DataRow dr) where T : EntityObject
        {
            T entity = Activator.CreateInstance<T>();

            if (dr == null) return entity;

            PropertyInfo[] properties = entity.GetType().GetProperties();
            foreach (PropertyInfo info in properties)
            {
                if (!dr.Table.Columns.Contains(info.Name)) continue;

                if (dr[info.Name] is DBNull)
                    info.SetValue(entity, null, null);
                else
                    info.SetValue(entity, dr[info.Name], null);
            }

            return entity;
        }

    }
}
